package com.bieyang.anjia.ui.activity;

import org.apache.http.ReasonPhraseCatalog;
import org.webrtc.mqttclientsample.LogUtis;
import org.webrtc.mqttclientsample.Message;
import org.webrtc.mqttclientsample.MessageService;

import android.annotation.SuppressLint;
import android.app.Dialog;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import android.text.Html;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.LoginTypeEnum;
import com.bieyang.anjia.module.User;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.refresh.BasicHandler;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.ShowProgress;
import com.bieyang.anjia.utils.SubUtils;

import com.umeng.analytics.MobclickAgent;

import de.greenrobot.event.EventBus;

public class AcLogin extends BaseActivity implements OnClickListener {
	protected static final int UPDATA = 0;
	protected static final int PUSHSERVICE_ISRUN = 1;
	protected static final int OK = -555;
	protected static final int MAIN_OK = -553;
	protected static final int SUB_OK = -552;
	public EditText editUser, editPassword;
	public TextView textForget;
	public CheckBox cbRemeber;
	private String mUserID;
	private String mPassword;
	protected Dialog dialog;
	// private AppMain appMain;
	ImageView loginDomo;

	private ShowProgress progressDialog;
	protected String imsi;
	boolean isAutoLogin;
	public RadioGroup streamType;
	int stream;
	 RadioButton maintype,subtype;

	Context con;
	Button btnBack, btnLogin;
	public static final String REGISTRATION_ID = "RegistrationId";
	public static boolean isForeground = false;
	// for receive customer msg from jpush server
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	static String uuid;
	static String userName;
	static String passWord;
	Intent intent;

	MyServiceConnection conn;

	@SuppressLint("HandlerLeak")
	private Handler Uihandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.LOGIN_SUCESS:
				// Show.toast(con, R.string.tip_login_ok);
				if (null != progressDialog)
					progressDialog.dismiss();
				saveLoginInfo();
				PubService.isrun = true;
				Intent it = new Intent(AcLogin.this, PubService.class); // 开启服务
				startService(it);

				/*
				 * register call
				 */
				conn = new MyServiceConnection();
				Intent serviceIntent = new Intent(con, MessageService.class);
				bindService(serviceIntent, conn, BIND_AUTO_CREATE);

				registerEvent();
				MessageService.startService(con, SubUtils.getUuid(con));

				if (0 == stream) {
					App.isLogin = true;
					SharedPrefsUtil.putValue(App.mContext, "phone", userName);
					SharedPrefsUtil.putValue(con, "loginType", "M");
					intent = new Intent(AcLogin.this, AcMain.class);
					startActivity(intent);
					finish();
				} else {
					SharedPrefsUtil.putValue(con, "subIsLogin", true);
					SharedPrefsUtil.putValue(con, "loginType", "C");
					intent = new Intent(AcLogin.this, SubMain.class);
					startActivity(intent);
					finish();
				}

				break;
			case Constants.LOGIN_NO_USER: // no user
				if (null != progressDialog)
					progressDialog.dismiss();
				Show.toast(con, R.string.tip_no_user);
				break;
			case Constants.LOGIN_WRONG_PASSWORD: // wrong password
				if (null != progressDialog)
					progressDialog.dismiss();
				Show.toast(con, R.string.tip_wrong_password);
				break;
			case Constants.LOGIN_SUB_NO: // wrong password
				if (null != progressDialog)
					progressDialog.dismiss();
				Show.toast(con, R.string.tip_sub_no);
				break;

			case Constants.LOGIN_FAIL:
				if (null != progressDialog)
					progressDialog.dismiss();
				Show.toast(con, R.string.tip_login_fail);
				break;
			default:
				break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_login);
		// JPushInterface.init(getApplicationContext());
		App.mContext = AcLogin.this;
		con = AcLogin.this;
		BasicHandler.init(this.getApplication());
		// appMain = (AppMain) getApplicationContext();
		editUser = (EditText) findViewById(R.id.et_user);
		editPassword = (EditText) findViewById(R.id.et_password);
		// textRegister = (TextView) findViewById(R.id.txt_register);
		textForget = (TextView) findViewById(R.id.txt_forget);
		streamType = (RadioGroup) findViewById(R.id.stream_type);
		
		   maintype= (RadioButton) findViewById(R.id.maintype);
		   subtype= (RadioButton) findViewById(R.id.subtype);

		// loginDomo = (ImageView) findViewById(R.id.login_demo);
		String s1 = getString(R.string.forget_pass);
		// textRegister.setText(Html.fromHtml("<u>" + s + "</u>"));
		textForget.setText(Html.fromHtml("<u>" + s1 + "</u>"));

		// textRegister.setOnClickListener(this);
		textForget.setOnClickListener(this);

		btnLogin = (Button) findViewById(R.id.btn_login);
		btnLogin.setOnClickListener(this);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);
		
		
		
		if("C".equals(SharedPrefsUtil.getStringValue(con, "loginType", ""))){
			 subtype.setChecked(true);
			 maintype.setChecked(false); 
		}else{
			 subtype.setChecked(false);
			 maintype.setChecked(true); 
		}
		

		if (null == progressDialog) {
			progressDialog = new ShowProgress(con);
			progressDialog.setMessage(R.string.loadingText);
		}

	}

	void login() {

		uuid = SubUtils.getUuid(con);
		User user = new User();
		user.setCardNo(userName);
		user.setPassword(passWord);
		user.setUuid(uuid);

		if (0 == stream) {
			user.setType(LoginTypeEnum.MAIN);
			SharedPrefsUtil.putValue(App.mContext, "loginType", "M");
		} else {
			user.setType(LoginTypeEnum.CLIENT);
			SharedPrefsUtil.putValue(App.mContext, "loginType", "C");
		}
		progressDialog.show();
		App.netManager.login(con, user, Uihandler);

	}

	void initeDate() {
		editUser.setText(mUserID);
		CharSequence etusere = editUser.getText();
		if (etusere instanceof Spannable) {//
			Spannable spanText = (Spannable) etusere;
			Selection.setSelection(spanText, etusere.length());
		}
		if (cbRemeber.isChecked()) {
			editPassword.setText(mPassword);
		}
		// imsi = Utils.getImsi(this);
	}

	@Override
	protected void onResume() {
		isForeground = true;
		super.onResume();

		editUser.setText(SharedPrefsUtil.getStringValue(App.mContext, "phone",
				""));
		editPassword.setText(SharedPrefsUtil.getStringValue(App.mContext,
				"password", ""));

		JPushInterface.onResume(getApplicationContext());
	}

	@Override
	protected void onPause() {
		isForeground = false;
		super.onPause();
		JPushInterface.onPause(getApplicationContext());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (null != conn)
			unbindService(conn);
		EventBus.getDefault().unregister(this);
		MobclickAgent.onKillProcess(this);
		LogUtis.log("Video destory..........");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack:
			goBack();

			break;

		// case R.id.txt_register:
		// startActivity(new Intent(this, AcRegister.class));
		//
		// break;
		case R.id.txt_forget:
			startActivity(new Intent(this, AcFindPassword.class).putExtra(
					"isLogin", true));
			break;
		case R.id.clear_btn:
			editUser.setText("");
			break;

		case R.id.btn_login:

			if (streamType.getCheckedRadioButtonId() == R.id.maintype) {
				stream = 0;
			} else {
				stream = 1;
			}

			userName = editUser.getText().toString().trim();
			passWord = editPassword.getText().toString();

			if (checkUser(userName, passWord)) {
				login();
			}

			break;

		default:
			break;
		}

	}

	public void LoginServer(boolean isLoginLocal) {
		if (!CheckInput(isLoginLocal))//
		{
			return;
		}

		if (!isLoginLocal) {
			progressDialog.show();
		}
	}

	void LoginThread(final String address, final int port,
			final String userName, final String password,
			final boolean isLoginLocal) {

	}

	/**
	 * 
	 * 
	 * @return
	 */
	public boolean CheckInput(boolean isLoginLocal) {

		if (TextUtils.isEmpty(editUser.getText().toString())) {

			Show.toast(this, R.string.enter_user_name);
			return false;
		}
		if (TextUtils.isEmpty(editPassword.getText().toString())) {

			Show.toast(this, R.string.enter_password);
			return false;
		}

		return true;
	}

	void saveLoginInfo() {
		SharedPrefsUtil.putValue(con, "phone", userName);
		SharedPrefsUtil.putValue(con, "password", passWord);
		if (0 == stream)
			SharedPrefsUtil.putValue(con, "loginMain", true);
		else
			SharedPrefsUtil.putValue(con, "loginMain", false);

	}

	public boolean checkUser(String name, String pass) {

		if (!("".equals(name) || "".equals(pass))) {
			if (11 != name.length()) {
				Show.toast(this, R.string.input_right_phone);
				return false;
			}
			if (pass.length() < 6) {
				editPassword.setError(getResources().getString(
						R.string.error_invalid_password));
				editPassword.requestFocus();
				return false;
			} else {
				return true;
			}
		} else {
			Show.toast(this, R.string.input_not_empty);
			return false;
		}

	}

	private class MyServiceConnection implements
			android.content.ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

	}

	private void registerEvent() {
		EventBus.getDefault().register(this, "onMessage", Message.class);
	}

	public void onMessage(final Message message) {
		LogUtis.log("from:" + message.getFrom() + "," + "to:" + message.getTo()
				+ "," + "content:" + message.getContent() + "," + "type:"
				+ message.getType());
		switch (message.getType()) {
		// case CHAT:
		// mReceiveMessage.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// mReceiveMessage.setText(mReceiveMessage.getText() + "\n"
		// + "来自" + message.getFrom() + "说:"
		// + message.getContent());
		// }
		// });
		// break;

		case PHONE:

			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		} else {

			return super.onKeyDown(keyCode, event);
		}
	}

	void goBack() {
		Intent intent = new Intent(con, AcTiYan.class);
		startActivity(intent);
		finish();
	}

}
